package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.vo.AttrAttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrGroupWithAttrsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    AttrService attrService;
    @Autowired
    AttrAttrgroupRelationService relationService;

    @Autowired
    AttrDao attrDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCategoryId(Map<String, Object> params, Long catelogId) {
        String key = (String) params.get("key");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
        if (catelogId != 0) {
            //不等于0,根据查询条件带分类
            wrapper.eq("catelog_id", catelogId);
        }
        if (StringUtils.isNotBlank(key)) {
            //key有值  进行模糊查询  attr_group_name  attr_group_id
            wrapper.like("attr_group_name", key).or().like("attr_group_id", key);
        }
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params), wrapper);
        return new PageUtils(page);

    }

    @Override
    public List<AttrEntity> attrAttrGrRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<AttrEntity> collect = relationEntities.stream().map((relation) -> {
            if (relation.getAttrId() != null) {
                AttrEntity attrEntity = attrDao.selectById(relation.getAttrId());
                return attrEntity;
            }
            return null;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 当前分组没有关联的属性
     *
     * @param attrGroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils attrAttrGroupNoRelation(Long attrGroupId, Map<String, Object> params) {
        /**
         * 1，当前分组只能关联当前分类下的属性
         * 2，当前分类下的分组已经关联的属性不能被当前分组关联
         * 3，查出当前分类下的所有基本属性，并排除已经被当前分类下的分组关联过的属性
         */
        //查出当前分类
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //查出当前分类下的所有分组 groupEntities
        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper
                <AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIds = groupEntities.stream().map((e) -> {
            return e.getAttrGroupId();
        }).collect(Collectors.toList());
        //该分类下的分组下的所有关联关系
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList
                (new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .in("attr_group_id", groupIds));
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if (relationEntities.size() > 0) {
            //如果其他分组有关联属性，查出其他分组已经关联了的属性
            List<Long> collect = relationEntities.stream().map((e) -> {
                return e.getAttrId();
            }).collect(Collectors.toList());
            //除去已经被关联了的属性，
            wrapper.notIn("attr_id", collect);
        }
        //如果带了关键字查询
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.eq("attr_id", key).or().eq("attr_name", key);
        }
        IPage<AttrEntity> page = attrService.page(new Query<AttrEntity>().getPage(params), wrapper.eq("attr_type",
                ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()));
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
//        //1、当前分组只能关联自己所属的分类里面的所有属性
//        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
//        Long catelogId = attrGroupEntity.getCatelogId();
//        // 2、当前分组只能别的分组没有引用的属性																									并且这个分组的id不是我当前正在查的id
//        //2.1)、当前分类下的其他分组
//        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
//        // 得到当前分类下面的所有分组id
//        List<Long> collect = group.stream().map(item -> {
//            return item.getAttrGroupId();
//        }).collect(Collectors.toList());
//
//        //2.2)、查询这些分组关联的属性
//        List<AttrAttrgroupRelationEntity> groupId = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
//        // 再次获取跟这些分组有关的属性id的集合
//        List<Long> attrIds = groupId.stream().map(item -> {
//            return item.getAttrId();
//        }).collect(Collectors.toList());
//
//        //2.3)、从当前分类的所有属性中移除这些属性；[因这些分组已经存在被选了 就不用再显示了]
//        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", 1);
//        if(attrIds != null && attrIds.size() > 0){
//            wrapper.notIn("attr_id", attrIds);
//        }
//        // 当搜索框中有key并且不为空的时候 进行模糊查询
//        if (null !=  params) {
//            String key = (String) params.get("key");
//            if(!org.springframework.util.StringUtils.isEmpty(key)){
//                wrapper.and((w)->{
//                    w.eq("attr_id",key).or().like("attr_name",key);
//                });
//            }
//        }
//        // 将最后返回的结果进行封装
//        IPage<AttrEntity> page = attrService.page(new Query<AttrEntity>().getPage(params), wrapper);
//
//        PageUtils pageUtils = new PageUtils(page);
//        return pageUtils;

    }

    @Override
    public void deleteAttrRelation(AttrAttrGroupRelationVo[] relationVo) {
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(relationVo).stream().map((e) -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(e, entity);
            return entity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.batchDeleAttrRelation(entities);
    }

    @Transactional
    @Override
    public void removeGroup(List<Long> attrGroupIds) {
        attrGroupDao.deleteBatchIds(attrGroupIds);
        //删除分组后,分组和属性的关系也要一起删除
        Map<String, Object> map = new HashMap<>();
        for (Long id : attrGroupIds) {
            map.put("attr_group_id", id);
        }
        attrAttrgroupRelationDao.deleteByMap(map);
    }

    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupByCatelogId(Long catelogId) {
        //查询商品分类下的所有分组
        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        if (groupEntities != null && groupEntities.size() > 0) {
            List<AttrGroupWithAttrsVo> attrGroupWithAttrsVos = groupEntities.stream().map((item) -> {
                AttrGroupWithAttrsVo attrGroupWithAttrsVo = new AttrGroupWithAttrsVo();
                BeanUtils.copyProperties(item, attrGroupWithAttrsVo);
                //根据groupid查询属性
                if (null != item.getAttrGroupId()) {
                    List<AttrEntity> attrs = relationService.getAttrsByAttrGroupId(item.getAttrGroupId());
                    attrGroupWithAttrsVo.setAttrs(attrs);
                }
                return attrGroupWithAttrsVo;
            }).collect(Collectors.toList());
        }

        return null;
    }
}

